home *** CD-ROM | disk | FTP | other *** search
/ Language/OS - Multiplatform Resource Library / LANGUAGE OS.iso / cpp_libs / cool / cool.lha / ice / pisces / diff / diff3.c < prev    next >
Encoding:
C/C++ Source or Header  |  1991-09-04  |  40.8 KB  |  1,508 lines

  1. /* Three-way file comparison program (diff3) for Project GNU
  2.    Copyright (C) 1988, 1989 Free Software Foundation, Inc.
  3.  
  4.    This program is free software; you can redistribute it and/or modify
  5.    it under the terms of the GNU General Public License as published by
  6.    the Free Software Foundation; either version 1, or (at your option)
  7.    any later version.
  8.  
  9.    This program is distributed in the hope that it will be useful,
  10.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  11.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12.    GNU General Public License for more details.
  13.  
  14.    You should have received a copy of the GNU General Public License
  15.    along with this program; if not, write to the Free Software
  16.    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */
  17.  
  18.  
  19. /* Written by Randy Smith */
  20.  
  21. #ifdef __STDC__
  22. #define VOID void
  23. #else
  24. #define VOID char
  25. #endif
  26.  
  27. /* 
  28.  * Include files.
  29.  */
  30. #include <stdio.h>
  31. #include <ctype.h>
  32.  
  33. #ifdef USG
  34. #include <fcntl.h>
  35. #ifdef os2
  36. #include <memory.h>
  37. #endif
  38.  
  39. /* Define needed BSD functions in terms of sysV library.  */
  40.  
  41. #define bcopy(s,d,n)    memcpy((d),(s),(n))
  42. #define bcmp(s1,s2,n)    memcmp((s1),(s2),(n))
  43. #define bzero(s,n)    memset((s),0,(n))
  44.  
  45. #define dup2(f,t)    (close(t),fcntl((f),F_DUPFD,(t)))
  46.  
  47. #define vfork    fork
  48. #define index    strchr
  49. #define rindex    strrchr
  50. #endif
  51. /*
  52.  * Internal data structures and macros for the diff3 program; includes
  53.  * data structures for both diff3 diffs and normal diffs.
  54.  */
  55.  
  56. /*
  57.  * Different files within a diff
  58.  */
  59. #define    FILE0    0
  60. #define    FILE1    1
  61. #define    FILE2    2
  62.  
  63. /*
  64.  * Three way diffs are build out of two two-way diffs; the file which
  65.  * the two two-way diffs share is:
  66.  */
  67. #define    FILEC    FILE0
  68.  
  69. /* The ranges are indexed by */
  70. #define    START    0
  71. #define    END    1
  72.  
  73. enum diff_type {
  74.   ERROR,            /* Should not be used */
  75.   ADD,                /* Two way diff add */
  76.   CHANGE,            /* Two way diff change */
  77.   DELETE,            /* Two way diff delete */
  78.   DIFF_ALL,            /* All three are different */
  79.   DIFF_1ST,            /* Only the first is different */
  80.   DIFF_2ND,            /* Only the second */
  81.   DIFF_3RD            /* Only the third */
  82. };
  83.  
  84. /* Two-way diff */
  85. struct diff_block {
  86.   int ranges[2][2];            /* Ranges are inclusive */
  87.   char **lines[2];        /* The actual lines (may contain nulls) */
  88.   int *lengths[2];        /* The lengths of the lines (since nulls) */
  89.   struct diff_block *next;
  90. };
  91.  
  92. /* Three-way diff */
  93.  
  94. struct diff3_block {
  95.   enum diff_type correspond;    /* Type of diff */
  96.   int ranges[3][2];            /* Ranges are inclusive */
  97.   char **lines[3];        /* The actual lines (may contain nulls) */
  98.   int *lengths[3];        /* The lengths of the lines (since nulls) */
  99.   struct diff3_block *next;
  100. };
  101.  
  102. /*
  103.  * Access the ranges on a diff block.
  104.  */
  105. #define    D_LOWLINE(diff, filenum)    \
  106.   ((diff)->ranges[filenum][START])
  107. #define    D_HIGHLINE(diff, filenum)    \
  108.   ((diff)->ranges[filenum][END])
  109. #define    D_NUMLINES(diff, filenum)    \
  110.   (D_HIGHLINE((diff), (filenum)) - D_LOWLINE((diff), (filenum)) + 1)
  111.  
  112. /*
  113.  * Access the line numbers in a file in a diff by absolute line number
  114.  * (i.e. line number within the original file).  Note that these are
  115.  * lvalues and can be used for assignment.
  116.  */
  117. #define    D_LINENUM(diff, filenum, linenum)    \
  118.   (*((diff)->lines[filenum] + linenum - D_LOWLINE((diff), (filenum))))
  119. #define    D_LINELEN(diff, filenum, linenum)    \
  120.   (*((diff)->lengths[filenum] + linenum - D_LOWLINE((diff), (filenum))))
  121.  
  122. /*
  123.  * Access the line numbers in a file in a diff by relative line
  124.  * numbers (i.e. line number within the diff itself).  Note that these
  125.  * are lvalues and can be used for assignment.
  126.  */
  127. #define    D_RELNUM(diff, filenum, linenum)    \
  128.   (*((diff)->lines[filenum] + linenum))
  129. #define    D_RELLEN(diff, filenum, linenum)    \
  130.   (*((diff)->lengths[filenum] + linenum))
  131.  
  132. /*
  133.  * And get at them directly, when that should be necessary.
  134.  */
  135. #define    D_LINEARRAY(diff, filenum)    \
  136.   ((diff)->lines[filenum])
  137. #define    D_LENARRAY(diff, filenum)    \
  138.   ((diff)->lengths[filenum])
  139.  
  140. /*
  141.  * Next block.
  142.  */
  143. #define    D_NEXT(diff)    ((diff)->next)
  144.  
  145. /*
  146.  * Access the type of a diff3 block.
  147.  */
  148. #define    D3_TYPE(diff)    ((diff)->correspond)
  149.  
  150. /*
  151.  * Line mappings based on diffs.  The first maps off the top of the
  152.  * diff, the second off of the bottom.
  153.  */
  154. #define    D_HIGH_MAPLINE(diff, fromfile, tofile, lineno)    \
  155.   ((lineno)                        \
  156.    - D_HIGHLINE ((diff), (fromfile))            \
  157.    + D_HIGHLINE ((diff), (tofile)))
  158.  
  159. #define    D_LOW_MAPLINE(diff, fromfile, tofile, lineno)    \
  160.   ((lineno)                        \
  161.    - D_LOWLINE ((diff), (fromfile))            \
  162.    + D_LOWLINE ((diff), (tofile)))
  163.  
  164. /*
  165.  * General memory allocation function.
  166.  */
  167. #define    ALLOCATE(number, type)    \
  168.   (type *) xmalloc ((number) * sizeof (type))
  169.  
  170. /*
  171.  * Options variables for flags set on command line.
  172.  *
  173.  * EDSCRIPT: Write out an ed script instead of the standard diff3 format.
  174.  *
  175.  * FLAGGING: Indicates that in the case of overlapping diffs (type
  176.  * DIFF_ALL), the lines which would normally be deleted from file 1
  177.  * should be preserved with a special flagging mechanism.
  178.  *
  179.  * DONT_WRITE_OVERLAP: 1 if information for overlapping diffs should
  180.  * not be output.
  181.  *
  182.  * DONT_WRITE_SIMPLE: 1 if information for non-overlapping diffs
  183.  * should not be output. 
  184.  *
  185.  * FINALWRITE: 1 if a :wq should be included at the end of the script
  186.  * to write out the file being edited.
  187.  */
  188. int edscript;
  189. int flagging;
  190. int dont_write_overlap;
  191. int dont_write_simple;
  192. int finalwrite;
  193.  
  194. extern int optind;
  195.  
  196. char *argv0;
  197.  
  198. /*
  199.  * Forward function declarations.
  200.  */
  201. struct diff_block *process_diff ();
  202. struct diff3_block *make_3way_diff ();
  203. void output_diff3 ();
  204. int output_diff3_edscript ();
  205. void usage ();
  206.  
  207. struct diff3_block *using_to_diff3_block ();
  208. int copy_stringlist ();
  209. struct diff3_block *create_diff3_block ();
  210. int compare_line_list ();
  211.  
  212. int read_diff ();
  213. enum diff_type process_diff_control ();
  214. char *scan_diff_line ();
  215.  
  216. struct diff3_block *reverse_diff3_blocklist ();
  217.  
  218. VOID *xmalloc ();
  219. VOID *xrealloc ();
  220.  
  221. /*
  222.  * No options take arguments.  "i" is my own addition; it stands for
  223.  * "include write command", to emulate system V behavior.
  224.  */
  225. #define    ARGSTRING    "eix3EX"
  226.  
  227. char diff_program[] = DIFF_PROGRAM;
  228.  
  229. /*
  230.  * Main program.  Calls diff twice on two pairs of input files,
  231.  * combines the two diffs, and outputs them.
  232.  */
  233. main (argc, argv)
  234.      int argc;
  235.      char **argv;
  236. {
  237.   int c;
  238.   int mapping [3];
  239.   int shiftmap;
  240.   int incompat;
  241.   int overlap_count;
  242.   struct diff_block *thread1, *thread2;
  243.   struct diff3_block *diff;
  244.  
  245.   edscript = flagging = dont_write_overlap
  246.     = dont_write_simple = finalwrite = 0;
  247.   incompat = shiftmap = 0;
  248.  
  249.   argv0 = argv[0];
  250.   
  251.   while ((c = getopt (argc, argv, ARGSTRING)) != EOF)
  252.     {
  253.       edscript = 1;
  254.       switch (c)
  255.     {
  256.     case 'x':
  257.       dont_write_simple = 1;
  258.       incompat++;
  259.       break;
  260.     case '3':
  261.       dont_write_overlap = 1;
  262.       incompat++;
  263.       break;
  264.     case 'i':
  265.       finalwrite = 1;
  266.       incompat++;
  267.       break;
  268.     case 'X':
  269.       dont_write_simple = 1;
  270.       /* Falls through */
  271.     case 'E':
  272.       flagging = 1;
  273.       /* Falls through */
  274.     case 'e':
  275.       incompat++;
  276.       break;
  277.     case '?':
  278.     default:
  279.       usage ();
  280.       /* NOTREACHED */
  281.     }
  282.     }
  283.  
  284.   if (incompat > 1)        /* Make sure you only have one of a */
  285.                 /* set of arguments */
  286.     usage ();
  287.   
  288.   if (argc - optind != 3)
  289.     usage ();
  290.  
  291.   if (*argv[optind] == '-' && *(argv[optind] + 1) == '\0')
  292.     {
  293.       /* Sigh.  We've got standard input as the first arg. We can't */
  294.       /* call diff twice on stdin */
  295.       mapping [0] = 1;
  296.       mapping [1] = 2;
  297.       mapping [2] = 0;
  298.       shiftmap = 1;
  299.     }
  300.   else
  301.     {
  302.       /* Normal, what you'd expect */
  303.       mapping [0] = 0;
  304.       mapping [1] = 1;
  305.       mapping [2] = 2;
  306.       shiftmap = 0;
  307.     }
  308.  
  309.   if (shiftmap)
  310.     {
  311.       thread1 = process_diff (argv[optind + 2], argv[optind]);
  312.       thread2 = process_diff (argv[optind + 2], argv[optind + 1]);
  313.     }
  314.   else
  315.     {
  316.       thread1 = process_diff (argv[optind], argv[optind + 1]);
  317.       thread2 = process_diff (argv[optind], argv[optind + 2]);
  318.     }
  319.   diff = make_3way_diff (thread1, thread2);
  320.   if (edscript)
  321.     overlap_count
  322.       = output_diff3_edscript (stdout, diff, mapping, argv[optind],
  323.                    argv[optind + 1], argv[optind + 2]);
  324.   else
  325.     output_diff3 (stdout, diff, mapping);
  326.  
  327.   if (edscript && overlap_count > 0)
  328.     /* We don't return overlap_count since it could overflow;
  329.        exit status is just 8 bits.  */
  330.     exit (1);
  331.   exit (0);
  332. }
  333.       
  334. /*
  335.  * Explain, patiently and kindly, how to use this program.  Then exit.
  336.  */
  337. void
  338. usage ()
  339. {
  340.   fprintf (stderr, "Usage:\t%s [ -exEX3 ] [ -i ] file1 file2 file3\n",
  341.        argv0);
  342.   fprintf (stderr, "\tOnly one of [exEX3] allowed\n");
  343.   exit (1);
  344. }
  345.  
  346. /*
  347.  * Routines that combine the two diffs together into one.  The
  348.  * algorithm used follows:
  349.  *
  350.  *   File0 is shared in common between the two diffs.
  351.  *   Diff01 is the diff between 0 and 1.
  352.  *   Diff02 is the diff between 0 and 2.
  353.  *
  354.  *     1) Find the range for the first block in File0.
  355.  *          a) Take the lowest of the two ranges (in File0) in the two
  356.  *             current blocks (one from each diff) as being the low
  357.  *             water mark.  Assign the upper end of this block as
  358.  *             being the high water mark and move the current block up
  359.  *             one.  Mark the block just moved over as to be used.
  360.  *        b) Check the next block in the diff that the high water
  361.  *             mark is *not* from.  
  362.  *           
  363.  *           *If* the high water mark is above
  364.  *             the low end of the range in that block, 
  365.  * 
  366.  *               mark that block as to be used and move the current
  367.  *                 block up.  Set the high water mark to the max of
  368.  *                 the high end of this block and the current.  Repeat b.
  369.  * 
  370.  *       2) Find the corresponding ranges in Files1 (from the blocks
  371.  *          in diff01; line per line outside of diffs) and in File2.
  372.  *          Create a diff3_block, reserving space as indicated by the ranges.
  373.  *        
  374.  *     3) Copy all of the pointers for file0 in.  At least for now,
  375.  *          do bcmp's between corresponding strings in the two diffs.
  376.  *        
  377.  *     4) Copy all of the pointers for file1 and 2 in.  Get what you
  378.  *          need from file0 (when there isn't a diff block, it's
  379.  *          identical to file0 within the range between diff blocks).
  380.  *        
  381.  *     5) If the diff blocks you used came from only one of the two
  382.  *         strings of diffs, then that file (i.e. the one other than
  383.  *         file 0 in that diff) is the odd person out.  If you used
  384.  *         diff blocks from both sets, check to see if files 1 and 2 match:
  385.  *        
  386.  *            Same number of lines?  If so, do a set of bcmp's (if a
  387.  *          bcmp matches; copy the pointer over; it'll be easier later
  388.  *          if you have to do any compares).  If they match, 1 & 2 are
  389.  *          the same.  If not, all three different.
  390.  * 
  391.  *   Then you do it again, until you run out of blocks. 
  392.  * 
  393.  */
  394.  
  395. /* 
  396.  * This routine makes a three way diff (chain of diff3_block's) from two
  397.  * two way diffs (chains of diff_block's).  It is assumed that each of
  398.  * the two diffs passed are off of the same file (i.e. that each of the
  399.  * diffs were made "from" the same file).  The three way diff pointer
  400.  * returned will have numbering 0--the common file, 1--the other file
  401.  * in diff1, and 2--the other file in diff2.
  402.  */
  403. struct diff3_block *
  404. make_3way_diff (thread1, thread2)
  405.      struct diff_block *thread1, *thread2;
  406. {
  407. /*
  408.  * This routine works on the two diffs passed to it as threads.
  409.  * Thread number 0 is diff1, thread number 1 is diff2.  The USING
  410.  * array is set to the base of the list of blocks to be used to
  411.  * construct each block of the three way diff; if no blocks from a
  412.  * particular thread are to be used, that element of the using array
  413.  * is set to 0.  The elements LAST_USING array are set to the last
  414.  * elements on each of the using lists.
  415.  *
  416.  * The HIGH_WATER_MARK is set to the highest line number in File 0
  417.  * described in any of the diffs in either of the USING lists.  The
  418.  * HIGH_WATER_THREAD names the thread.  Similarly the BASE_WATER_MARK
  419.  * and BASE_WATER_THREAD describe the lowest line number in File 0
  420.  * described in any of the diffs in either of the USING lists.  The
  421.  * HIGH_WATER_DIFF is the diff from which the HIGH_WATER_MARK was
  422.  * taken. 
  423.  *
  424.  * The HIGH_WATER_DIFF should always be equal to LAST_USING
  425.  * [HIGH_WATER_THREAD].  The OTHER_DIFF is the next diff to check for
  426.  * higher water, and should always be equal to
  427.  * CURRENT[HIGH_WATER_THREAD ^ 0x1].  The OTHER_THREAD is the thread
  428.  * in which the OTHER_DIFF is, and hence should always be equal to
  429.  * HIGH_WATER_THREAD ^ 0x1.
  430.  *
  431.  * The variable LAST_DIFF is kept set to the last diff block produced
  432.  * by this routine, for line correspondence purposes between that diff
  433.  * and the one currently being worked on.  It is initialized to
  434.  * ZERO_DIFF before any blocks have been created.
  435.  */
  436.  
  437.   struct diff_block
  438.     *using[2],
  439.     *last_using[2],
  440.     *current[2];
  441.  
  442.   int
  443.     high_water_mark;
  444.  
  445.   int
  446.     high_water_thread,
  447.     base_water_thread,
  448.     other_thread;
  449.  
  450.   struct diff_block
  451.     *high_water_diff,
  452.     *other_diff;
  453.  
  454.   struct diff3_block
  455.     *result,
  456.     *tmpblock,
  457.     *result_last,
  458.     *last_diff;
  459.  
  460.   static struct diff3_block zero_diff = {
  461.       ERROR,
  462.       { {0, 0}, {0, 0}, {0, 0} },
  463.       { (char **) 0, (char **) 0, (char **) 0 },
  464.       { (int *) 0, (int *) 0, (int *) 0 },
  465.       (struct diff3_block *) 0
  466.       };
  467.  
  468.   /* Initialization */
  469.   result = result_last = (struct diff3_block *) 0;
  470.   current[0] = thread1; current[1] = thread2;
  471.   last_diff = &zero_diff;
  472.  
  473.   /* Sniff up the threads until we reach the end */
  474.  
  475.   while (current[0] || current[1])
  476.     {
  477.       using[0] = using[1] = last_using[0] = last_using[1] =
  478.     (struct diff_block *) 0;
  479.  
  480.       /* Setup low and high water threads, diffs, and marks.  */
  481.       if (!current[0])
  482.     base_water_thread = 1;
  483.       else if (!current[1])
  484.     base_water_thread = 0;
  485.       else
  486.     base_water_thread =
  487.       (D_LOWLINE (current[0], FILE0) > D_LOWLINE (current[1], FILE0));
  488.  
  489.       high_water_thread = base_water_thread;
  490.       
  491.       high_water_diff = current[high_water_thread];
  492.     
  493. #if 0
  494.       /* low and high waters start off same diff */
  495.       base_water_mark = D_LOWLINE (high_water_diff, FILE0);
  496. #endif
  497.  
  498.       high_water_mark = D_HIGHLINE (high_water_diff, FILE0);
  499.  
  500.       /* Make the diff you just got info from into the using class */
  501.       using[high_water_thread]
  502.     = last_using[high_water_thread]
  503.     = high_water_diff;
  504.       current[high_water_thread] = high_water_diff->next;
  505.       last_using[high_water_thread]->next
  506.     = (struct diff_block *) 0;
  507.  
  508.       /* And mark the other diff */
  509.       other_thread = high_water_thread ^ 0x1;
  510.       other_diff = current[other_thread];
  511.  
  512.       /* Shuffle up the ladder, checking the other diff to see if it
  513.          needs to be incorporated */
  514.       while (other_diff
  515.          && D_LOWLINE (other_diff, FILE0) <= high_water_mark + 1)
  516.     {
  517.  
  518.       /* Incorporate this diff into the using list.  Note that
  519.          this doesn't take it off the current list */
  520.       if (using[other_thread])
  521.         last_using[other_thread]->next = other_diff;
  522.       else
  523.         using[other_thread] = other_diff;
  524.       last_using[other_thread] = other_diff;
  525.  
  526.       /* Take it off the current list.  Note that this following
  527.          code assumes that other_diff enters it equal to
  528.          current[high_water_thread ^ 0x1] */
  529.       current[other_thread]
  530.         = current[other_thread]->next;
  531.       other_diff->next
  532.         = (struct diff_block *) 0;
  533.  
  534.       /* Set the high_water stuff
  535.          If this comparison is equal, then this is the last pass
  536.          through this loop; since diff blocks within a given
  537.          thread cannot overlap, the high_water_mark will be
  538.          *below* the range_start of either of the next diffs. */
  539.  
  540.       if (high_water_mark < D_HIGHLINE (other_diff, FILE0))
  541.         {
  542.           high_water_thread ^= 1;
  543.           high_water_diff = other_diff;
  544.           high_water_mark = D_HIGHLINE (other_diff, FILE0);
  545.         }
  546.  
  547.       /* Set the other diff */
  548.       other_thread = high_water_thread ^ 0x1;
  549.       other_diff = current[other_thread];
  550.     }
  551.  
  552.       /* The using lists contain a list of all of the blocks to be
  553.          included in this diff3_block.  Create it.  */
  554.  
  555.       tmpblock = using_to_diff3_block (using, last_using,
  556.                        base_water_thread, high_water_thread,
  557.                        last_diff);
  558.  
  559.       if (!tmpblock)
  560.     fatal ("internal: screwup in format of diff blocks");
  561.  
  562.       /* Put it on the list */
  563.       if (result)
  564.     result_last->next = tmpblock;
  565.       else
  566.     result = tmpblock;
  567.       result_last = tmpblock;
  568.  
  569.       /* Setup corresponding lines correctly */
  570.       last_diff = tmpblock;
  571.     }
  572.   return result;
  573. }
  574.  
  575. /*
  576.  * using_to_diff3_block:
  577.  *   This routine takes two lists of blocks (from two separate diff
  578.  * threads) and puts them together into one diff3 block.
  579.  * It then returns a pointer to this diff3 block or 0 for failure.
  580.  *
  581.  * All arguments besides using are for the convenience of the routine;
  582.  * they could be derived from the using array.
  583.  * LAST_USING is a pair of pointers to the last blocks in the using
  584.  * structure.
  585.  * LOW_THREAD and HIGH_THREAD tell which threads contain the lowest
  586.  * and highest line numbers for File0.
  587.  * last_diff contains the last diff produced in the calling routine.
  588.  * This is used for lines mappings which would still be identical to
  589.  * the state that diff ended in.
  590.  *
  591.  * A distinction should be made in this routine between the two diffs
  592.  * that are part of a normal two diff block, and the three diffs that
  593.  * are part of a diff3_block.
  594.  */
  595. struct diff3_block *
  596. using_to_diff3_block (using, last_using, low_thread, high_thread, last_diff)
  597.      struct diff_block
  598.        *using[2],
  599.        *last_using[2];
  600.      int low_thread, high_thread;
  601.      struct diff3_block *last_diff;
  602. {
  603.   int lowc, highc, low1, high1, low2, high2;
  604.   struct diff3_block *result;
  605.   struct diff_block *ptr;
  606.   int i;
  607.   int current0line;
  608.   
  609.   /* Find the range in file0 */
  610.   lowc = using[low_thread]->ranges[0][START];
  611.   highc = last_using[high_thread]->ranges[0][END];
  612.  
  613.   /* Find the ranges in the other files.
  614.      If using[x] is null, that means that the file to which that diff
  615.      refers is equivalent to file 0 over this range */
  616.   
  617.   if (using[0])
  618.     {
  619.       low1 = D_LOW_MAPLINE (using[0], FILE0, FILE1, lowc);
  620.       high1 = D_HIGH_MAPLINE (last_using[0], FILE0, FILE1, highc); 
  621.     }
  622.   else
  623.     {
  624.       low1 = D_HIGH_MAPLINE (last_diff, FILEC, FILE1, lowc);
  625.       high1 = D_HIGH_MAPLINE (last_diff, FILEC, FILE1, highc);
  626.     }
  627.  
  628.   /*
  629.    * Note that in the following, we use file 1 relative to the diff,
  630.    * and file 2 relative to the corresponding lines struct.
  631.    */
  632.   if (using[1])
  633.     {
  634.       low2 = D_LOW_MAPLINE (using[1], FILE0, FILE1, lowc);
  635.       high2 = D_HIGH_MAPLINE (last_using[1], FILE0, FILE1, highc); 
  636.     }
  637.   else
  638.     {
  639.       low2 = D_HIGH_MAPLINE (last_diff, FILEC, FILE2, lowc);
  640.       high2 = D_HIGH_MAPLINE (last_diff, FILEC, FILE2, highc);
  641.     }
  642.  
  643.   /* Create a block with the appropriate sizes */
  644.   result = create_diff3_block (lowc, highc, low1, high1, low2, high2);
  645.  
  646.   /* Copy over all of the information for File 0.  Return with a zero
  647.      if any of the compares failed. */
  648.   for (ptr = using[0]; ptr; ptr = D_NEXT (ptr))
  649.     {
  650.       int result_offset = D_LOWLINE (ptr, FILE0) - lowc;
  651.       int copy_size
  652.     = D_HIGHLINE (ptr, FILE0) - D_LOWLINE (ptr, FILE0) + 1;
  653.       
  654.       if (!copy_stringlist (D_LINEARRAY (ptr, FILE0),
  655.                 D_LENARRAY (ptr, FILE0),
  656.                 D_LINEARRAY (result, FILEC) + result_offset,
  657.                 D_LENARRAY (result, FILEC) + result_offset,
  658.                 copy_size))
  659.     return 0;
  660.     }
  661.  
  662.   for (ptr = using[1]; ptr; ptr = D_NEXT (ptr))
  663.     {
  664.       int result_offset = D_LOWLINE (ptr, FILEC) - lowc;
  665.       int copy_size
  666.     = D_HIGHLINE (ptr, FILEC) - D_LOWLINE (ptr, FILEC) + 1;
  667.       
  668.       if (!copy_stringlist (D_LINEARRAY (ptr, FILE0),
  669.                 D_LENARRAY (ptr, FILE0),
  670.                 D_LINEARRAY (result, FILEC) + result_offset,
  671.                 D_LENARRAY (result, FILEC) + result_offset,
  672.                 copy_size))
  673.     return 0;
  674.     }
  675.  
  676.   /* Copy stuff for file 1.  First deal with anything that might be
  677.      before the first diff. */
  678.  
  679.   for (i = 0;
  680.        i + low1 < (using[0] ? D_LOWLINE (using[0], FILE1) : high1 + 1);
  681.        i++)
  682.     {
  683.       D_RELNUM (result, FILE1, i) = D_RELNUM (result, FILEC, i);
  684.       D_RELLEN (result, FILE1, i) = D_RELLEN (result, FILEC, i);
  685.     }
  686.   
  687.   for (ptr = using[0]; ptr; ptr = D_NEXT (ptr))
  688.     {
  689.       int result_offset = D_LOWLINE (ptr, FILE1) - low1;
  690.       int copy_size
  691.     = D_HIGHLINE (ptr, FILE1) - D_LOWLINE (ptr, FILE1) + 1;
  692.  
  693.       if (!copy_stringlist (D_LINEARRAY (ptr, FILE1),
  694.                 D_LENARRAY (ptr, FILE1),
  695.                 D_LINEARRAY (result, FILE1) + result_offset,
  696.                 D_LENARRAY (result, FILE1) + result_offset,
  697.                 copy_size))
  698.     return 0;
  699.  
  700.       /* Catch the lines between here and the next diff */
  701.       current0line = D_HIGHLINE (ptr, FILE0) + 1 - lowc;
  702.       for (i = D_HIGHLINE (ptr, FILE1) + 1 - low1;
  703.        i < (D_NEXT (ptr) ?
  704.         D_LOWLINE (D_NEXT (ptr), FILE1) :
  705.         high1 + 1) - low1;
  706.        i++)
  707.     {
  708.       D_RELNUM (result, FILE1, i)
  709.         = D_RELNUM (result, FILEC, current0line);
  710.       D_RELLEN (result, FILE1, i)
  711.         = D_RELLEN (result, FILEC, current0line++);
  712.     }
  713.     }
  714.  
  715.   /* Copy stuff for file 2.  First deal with anything that might be
  716.      before the first diff. */
  717.  
  718.   for (i = 0;
  719.        i + low2 < (using[1] ? D_LOWLINE (using[1], FILE1) : high2 + 1);
  720.        i++)
  721.     {
  722.       D_RELNUM (result, FILE2, i) = D_RELNUM (result, FILEC, i);
  723.       D_RELLEN (result, FILE2, i) = D_RELLEN (result, FILEC, i);
  724.     }
  725.   
  726.   for (ptr = using[1]; ptr; ptr = D_NEXT (ptr))
  727.     {
  728.       int result_offset = D_LOWLINE (ptr, FILE1) - low2;
  729.       int copy_size
  730.     = D_HIGHLINE (ptr, FILE1) - D_LOWLINE (ptr, FILE1) + 1;
  731.  
  732.       if (!copy_stringlist (D_LINEARRAY (ptr, FILE1),
  733.                 D_LENARRAY (ptr, FILE1),
  734.                 D_LINEARRAY (result, FILE2) + result_offset,
  735.                 D_LENARRAY (result, FILE2) + result_offset,
  736.                 copy_size))
  737.     return 0;
  738.  
  739.       /* Catch the lines between here and the next diff */
  740.       current0line = D_HIGHLINE (ptr, FILE0) + 1 - lowc;
  741.       for (i = D_HIGHLINE (ptr, FILE1) + 1 - low2;
  742.        i < (D_NEXT (ptr) ?
  743.         D_LOWLINE (D_NEXT (ptr), FILE1) :
  744.         high2 + 1) - low2;
  745.        i++)
  746.     {
  747.       D_RELNUM (result, FILE2, i)
  748.         = D_RELNUM (result, FILEC, current0line);
  749.       D_RELLEN (result, FILE2, i)
  750.         = D_RELLEN (result, FILEC, current0line++);
  751.     }
  752.     }
  753.  
  754.   /* Set correspond */
  755.   if (!using[0])
  756.     D3_TYPE (result) = DIFF_3RD;
  757.   else if (!using[1])
  758.     D3_TYPE (result) = DIFF_2ND;
  759.   else
  760.     {
  761.       int nl1
  762.     = D_HIGHLINE (result, FILE1) - D_LOWLINE (result, FILE1) + 1;
  763.       int nl2
  764.     = D_HIGHLINE (result, FILE2) - D_LOWLINE (result, FILE2) + 1;
  765.  
  766.       if (nl1 != nl2
  767.       || !compare_line_list (D_LINEARRAY (result, FILE1),
  768.                  D_LENARRAY (result, FILE1),
  769.                  D_LINEARRAY (result, FILE2),
  770.                  D_LENARRAY (result, FILE2),
  771.                  nl1))
  772.     D3_TYPE (result) = DIFF_ALL;
  773.       else
  774.     D3_TYPE (result) = DIFF_1ST;
  775.     }
  776.   
  777.   return result;
  778. }
  779.  
  780. /*
  781.  * This routine copies pointers from a list of strings to a different list
  782.  * of strings.  If a spot in the second list is already filled, it
  783.  * makes sure that it is filled with the same string; if not it
  784.  * returns 0, the copy incomplete.
  785.  * Upon successful completion of the copy, it returns 1.
  786.  */
  787. int
  788. copy_stringlist (fromptrs, fromlengths, toptrs, tolengths, copynum)
  789.      char *fromptrs[], *toptrs[];
  790.      int *fromlengths, *tolengths;
  791.      int copynum;
  792. {
  793.   register char
  794.     **f = fromptrs,
  795.     **t = toptrs;
  796.   register int
  797.     *fl = fromlengths,
  798.     *tl = tolengths;
  799.   
  800.   while (copynum--)
  801.     {
  802.       if (*t)
  803.     { if (*fl != *tl || bcmp (*f, *t, *fl)) return 0; }
  804.       else
  805.     { *t = *f ; *tl = *fl; }
  806.  
  807.       t++; f++; tl++; fl++;
  808.     }
  809.   return 1;
  810. }
  811.  
  812. /*
  813.  * Create a diff3_block, with ranges as specified in the arguments.
  814.  * Allocate the arrays for the various pointers (and zero them) based
  815.  * on the arguments passed.  Return the block as a result.
  816.  */
  817. struct diff3_block *
  818. create_diff3_block (low0, high0, low1, high1, low2, high2)
  819.      register int low0, high0, low1, high1, low2, high2;
  820. {
  821.   struct diff3_block *result = ALLOCATE (1, struct diff3_block);
  822.   int numlines;
  823.  
  824.   D3_TYPE (result) = ERROR;
  825.   D_NEXT (result) = 0;
  826.  
  827.   /* Assign ranges */
  828.   D_LOWLINE (result, FILE0) = low0;
  829.   D_HIGHLINE (result, FILE0) = high0;
  830.   D_LOWLINE (result, FILE1) = low1;
  831.   D_HIGHLINE (result, FILE1) = high1;
  832.   D_LOWLINE (result, FILE2) = low2;
  833.   D_HIGHLINE (result, FILE2) = high2;
  834.  
  835.   /* Allocate and zero space */
  836.   numlines = D_NUMLINES (result, FILE0);
  837.   if (numlines)
  838.     {
  839.       D_LINEARRAY (result, FILE0) = ALLOCATE (numlines, char *);
  840.       D_LENARRAY (result, FILE0) = ALLOCATE (numlines, int);
  841.       bzero (D_LINEARRAY (result, FILE0), (numlines * sizeof (char *)));
  842.       bzero (D_LENARRAY (result, FILE0), (numlines * sizeof (int)));
  843.     }
  844.   else
  845.     {
  846.       D_LINEARRAY (result, FILE0) = (char **) 0;
  847.       D_LENARRAY (result, FILE0) = (int *) 0;
  848.     }
  849.  
  850.   numlines = D_NUMLINES (result, FILE1);
  851.   if (numlines)
  852.     {
  853.       D_LINEARRAY (result, FILE1) = ALLOCATE (numlines, char *);
  854.       D_LENARRAY (result, FILE1) = ALLOCATE (numlines, int);
  855.       bzero (D_LINEARRAY (result, FILE1), (numlines * sizeof (char *)));
  856.       bzero (D_LENARRAY (result, FILE1), (numlines * sizeof (int)));
  857.     }
  858.   else
  859.     {
  860.       D_LINEARRAY (result, FILE1) = (char **) 0;
  861.       D_LENARRAY (result, FILE1) = (int *) 0;
  862.     }
  863.  
  864.   numlines = D_NUMLINES (result, FILE2);
  865.   if (numlines)
  866.     {
  867.       D_LINEARRAY (result, FILE2) = ALLOCATE (numlines, char *);
  868.       D_LENARRAY (result, FILE2) = ALLOCATE (numlines, int);
  869.       bzero (D_LINEARRAY (result, FILE2), (numlines * sizeof (char *)));
  870.       bzero (D_LENARRAY (result, FILE2), (numlines * sizeof (int)));
  871.     }
  872.   else
  873.     {
  874.       D_LINEARRAY (result, FILE2) = (char **) 0;
  875.       D_LENARRAY (result, FILE2) = (int *) 0;
  876.     }
  877.  
  878.   /* Return */
  879.   return result;
  880. }
  881.  
  882. /*
  883.  * Compare two lists of lines of text.
  884.  * Return 1 if they are equivalent, 0 if not.
  885.  */
  886. int
  887. compare_line_list (list1, lengths1, list2, lengths2, nl)
  888.      char *list1[], *list2[];
  889.      int *lengths1, *lengths2;
  890.      int nl;
  891. {
  892.   char
  893.     **l1 = list1,
  894.     **l2 = list2;
  895.   int
  896.     *lgths1 = lengths1,
  897.     *lgths2 = lengths2;
  898.   
  899.   while (nl--)
  900.     if (!*l1 || !*l2 || *lgths1 != *lgths2++
  901.     || bcmp (*l1++, *l2++, *lgths1++))
  902.       return 0;
  903.   return 1;
  904. }
  905.  
  906. /* 
  907.  * Routines to input and parse two way diffs.
  908.  */
  909.  
  910. extern char **environ;
  911.  
  912. #define    DIFF_CHUNK_SIZE    10000
  913.  
  914. struct diff_block *
  915. process_diff (filea, fileb)
  916.      char *filea, *fileb;
  917. {
  918.   char *diff_contents;
  919.   int diff_size;
  920.   char *scan_diff;
  921.   enum diff_type dt;
  922.   int i;
  923.   struct diff_block *block_list, *block_list_end, *bptr;
  924.  
  925.   diff_size = read_diff (filea, fileb, &diff_contents);
  926.   scan_diff = diff_contents;
  927.   bptr = block_list_end = block_list = (struct diff_block *) 0;
  928.  
  929.   while (scan_diff - diff_contents < diff_size)
  930.     {
  931.       bptr = ALLOCATE (1, struct diff_block);
  932.       bptr->next = 0;
  933.       bptr->lines[0] = bptr->lines[1] = (char **) 0;
  934.       bptr->lengths[0] = bptr->lengths[1] = (int *) 0;
  935.       
  936.       dt = process_diff_control (&scan_diff, bptr);
  937.       if (dt == ERROR) fatal ("Bad format in diff output");
  938.       if (*scan_diff != '\n') fatal ("Bad format in diff output");
  939.       scan_diff++;
  940.       
  941.       /* Force appropriate ranges to be null, if necessary */
  942.       switch (dt)
  943.     {
  944.     case ADD:
  945.       bptr->ranges[0][0]++;
  946.       break;
  947.     case DELETE:
  948.       bptr->ranges[1][0]++;
  949.       break;
  950.     case CHANGE:
  951.       break;
  952.     default:
  953.       fatal ("internal: Bad diff type in process_diff");
  954.       break;
  955.     }
  956.       
  957.       /* Allocate space for the pointers for the lines from filea, and
  958.      parcel them out among these pointers */
  959.       if (dt != ADD)
  960.     {
  961.       bptr->lines[0] = ALLOCATE ((bptr->ranges[0][END]
  962.                       - bptr->ranges[0][START] + 1),
  963.                      char *);
  964.       bptr->lengths[0] = ALLOCATE ((bptr->ranges[0][END]
  965.                     - bptr->ranges[0][START] + 1),
  966.                        int);
  967.       for (i = 0; i <= (bptr->ranges[0][END]
  968.                 - bptr->ranges[0][START]); i++)
  969.         scan_diff = scan_diff_line (scan_diff,
  970.                     &(bptr->lines[0][i]),
  971.                     &(bptr->lengths[0][i]),
  972.                     diff_contents + diff_size,
  973.                     '<');
  974.     }
  975.       
  976.       /* Get past the separator for changes */
  977.       if (dt == CHANGE)
  978.     {
  979.       if (strncmp (scan_diff, "---\n", 4))
  980.         fatal ("Bad diff format: bad change separator");
  981.       scan_diff += 4;
  982.     }
  983.       
  984.       /* Allocate space for the pointers for the lines from fileb, and
  985.      parcel them out among these pointers */
  986.       if (dt != DELETE)
  987.     {
  988.       bptr->lines[1] = ALLOCATE ((bptr->ranges[1][END]
  989.                       - bptr->ranges[1][START] + 1),
  990.                      char *);
  991.       bptr->lengths[1] = ALLOCATE ((bptr->ranges[1][END]
  992.                     - bptr->ranges[1][START] + 1),
  993.                        int);
  994.       for (i = 0; i <= (bptr->ranges[1][END]
  995.                 - bptr->ranges[1][START]); i++)
  996.         scan_diff = scan_diff_line (scan_diff,
  997.                     &(bptr->lines[1][i]),
  998.                     &(bptr->lengths[1][i]),
  999.                     diff_contents + diff_size,
  1000.                     '>');
  1001.     }
  1002.       
  1003.       /* Place this block on the blocklist */
  1004.       if (block_list_end)
  1005.     block_list_end->next = bptr;
  1006.       else
  1007.     block_list = bptr;
  1008.       
  1009.       block_list_end = bptr;
  1010.       
  1011.     }
  1012.  
  1013.   if (scan_diff - diff_contents != diff_size)
  1014.     fatal ("bad diff format; incomplete last line");
  1015.  
  1016.   return block_list;
  1017. }
  1018.  
  1019. /*
  1020.  * This routine will parse a normal format diff control string.  It
  1021.  * returns the type of the diff (ERROR if the format is bad).  All of
  1022.  * the other important information is filled into to the structure
  1023.  * pointed to by db, and the string pointer (whose location is passed
  1024.  * to this routine) is updated to point beyond the end of the string
  1025.  * parsed.  Note that only the ranges in the diff_block will be set by
  1026.  * this routine.
  1027.  *
  1028.  * If some specific pair of numbers has been reduced to a single
  1029.  * number, then both corresponding numbers in the diff block are set
  1030.  * to that number.  In general these numbers are interpetted as ranges
  1031.  * inclusive, unless being used by the ADD or DELETE commands.  It is
  1032.  * assumed that these will be special cased in a superior routine.  
  1033.  */
  1034.  
  1035. enum diff_type
  1036. process_diff_control (string, db)
  1037.      char **string;
  1038.      struct diff_block *db;
  1039. {
  1040.   char *s = *string;
  1041.   int holdnum;
  1042.   enum diff_type type;
  1043.  
  1044. /* These macros are defined here because they can use variables
  1045.    defined in this function.  Don't try this at home kids, we're
  1046.    trained professionals!
  1047.  
  1048.    Also note that SKIPWHITE only recognizes tabs and spaces, and
  1049.    that READNUM can only read positive, integral numbers */
  1050.  
  1051. #define    SKIPWHITE(s)    { while (*s == ' ' || *s == '\t') s++; }
  1052. #define    READNUM(s, num)    \
  1053.     { if (!isdigit (*s)) return ERROR; holdnum = 0;    \
  1054.       do { holdnum = (*s++ - '0' + holdnum * 10); }    \
  1055.       while (isdigit (*s)); (num) = holdnum; }
  1056.  
  1057.   /* Read first set of digits */
  1058.   SKIPWHITE (s);
  1059.   READNUM (s, db->ranges[0][START]);
  1060.  
  1061.   /* Was that the only digit? */
  1062.   SKIPWHITE(s);
  1063.   if (*s == ',')
  1064.     {
  1065.       /* Get the next digit */
  1066.       s++;
  1067.       READNUM (s, db->ranges[0][END]);
  1068.     }
  1069.   else
  1070.     db->ranges[0][END] = db->ranges[0][START];
  1071.  
  1072.   /* Get the letter */
  1073.   SKIPWHITE (s);
  1074.   switch (*s)
  1075.     {
  1076.     case 'a':
  1077.       type = ADD;
  1078.       break;
  1079.     case 'c':
  1080.       type = CHANGE;
  1081.       break;
  1082.     case 'd':
  1083.       type = DELETE;
  1084.       break;
  1085.     default:
  1086.       return ERROR;            /* Bad format */
  1087.     }
  1088.   s++;                /* Past letter */
  1089.   
  1090.   /* Read second set of digits */
  1091.   SKIPWHITE (s);
  1092.   READNUM (s, db->ranges[1][START]);
  1093.  
  1094.   /* Was that the only digit? */
  1095.   SKIPWHITE(s);
  1096.   if (*s == ',')
  1097.     {
  1098.       /* Get the next digit */
  1099.       s++;
  1100.       READNUM (s, db->ranges[1][END]);
  1101.       SKIPWHITE (s);        /* To move to end */
  1102.     }
  1103.   else
  1104.     db->ranges[1][END] = db->ranges[1][START];
  1105.  
  1106.   *string = s;
  1107.   return type;
  1108. }
  1109.  
  1110. int
  1111. read_diff (filea, fileb, output_placement)
  1112.      char *filea, *fileb;
  1113.      char **output_placement;
  1114. {
  1115.   char *argv[4];
  1116.   int fds[2];
  1117.   char *diff_result;
  1118.   long current_chunk_size;
  1119.   int bytes;
  1120.   int total;
  1121.  
  1122.   argv[0] = diff_program;
  1123.   argv[1] = filea;
  1124.   argv[2] = fileb;
  1125.   argv[3] = (char *) 0;
  1126.  
  1127.   pipe (fds);
  1128.  
  1129.   if (!fork ())
  1130.     {
  1131.       /* Child */
  1132.       dup2 (fds[1], 1);        /* Make stdout the pipe to the parent */
  1133.       /* Leave stdin alone; the diff may need it */
  1134.       execvp (diff_program, argv);
  1135.       perror_with_exit ("Exec failed");
  1136.     }
  1137.  
  1138.   close (fds[1]);        /* Prevent erroneous lack of EOF */
  1139.   current_chunk_size = DIFF_CHUNK_SIZE;
  1140.   diff_result = (char *) xmalloc (current_chunk_size);
  1141.   total = 0;
  1142.   do {
  1143.     bytes = myread (fds[0],
  1144.             diff_result + total,
  1145.             current_chunk_size - total);
  1146.     total += bytes;
  1147.     if (total == current_chunk_size)
  1148.       diff_result = (char *) xrealloc (diff_result, (current_chunk_size *= 2));
  1149.   } while (bytes);
  1150.  
  1151.   *output_placement = diff_result;
  1152.  
  1153.   return total;
  1154. }
  1155.  
  1156.  
  1157. /*
  1158.  * Scan a regular diff line (consisting of > or <, followed by a
  1159.  * space, followed by text (including nulls) up to a newline.
  1160.  *
  1161.  * This next routine began life as a macro and many parameters in it
  1162.  * are used as call-by-reference values.
  1163.  */
  1164. char *
  1165. scan_diff_line (scan_ptr, set_start, set_length, limit, firstchar)
  1166.      char *scan_ptr, **set_start;
  1167.      int *set_length;
  1168.      char *limit;
  1169.      char firstchar;
  1170. {
  1171.   char *line_ptr = scan_ptr + 2;
  1172.  
  1173.   if (!(scan_ptr[0] == (firstchar)
  1174.     && scan_ptr[1] == ' '))
  1175.     fatal ("Bad diff format; incorrect leading line chars");
  1176.  
  1177.   *set_start = line_ptr;
  1178.   while (*line_ptr != '\n') line_ptr++;
  1179.   
  1180.   if (line_ptr >= limit)
  1181.     fatal ("Bad diff format; overflow in parse");
  1182.  
  1183.   /* Don't include newline, but do return the beginning of the
  1184.      next line */
  1185.   *set_length = line_ptr - *set_start;
  1186.  
  1187.   return line_ptr + 1;
  1188. }
  1189.  
  1190. /*
  1191.  * This routine outputs a three way diff passed as a list of
  1192.  * diff3_block's.
  1193.  * The argument MAPPING is indexed by external file number (in the
  1194.  * argument list) and contains the internal file number (from the
  1195.  * diff passed).  This is important because the user expects his
  1196.  * outputs in terms of the argument list number, and the diff passed
  1197.  * may have been done slightly differently (if the first argument in
  1198.  * the argument list was the standard input, for example).
  1199.  */
  1200. void
  1201. output_diff3 (outputfile, diff, mapping)
  1202.      FILE *outputfile;
  1203.      struct diff3_block *diff;
  1204.      int mapping[3];
  1205. {
  1206.   int rev_mapping[3];
  1207.   static int eliminate[3] = { 1, 0, 0};
  1208.   int i;
  1209.   int oddoneout;
  1210.   char *cp;
  1211.   struct diff3_block *ptr;
  1212.   int line;
  1213.   int dontprint;
  1214.   static int skew_increment[3] = { 2, 3, 1 }; /* 0==>2==>1==>3 */
  1215.  
  1216.   for (i = 0; i < 3; i++)
  1217.     rev_mapping [mapping[i]] = i;
  1218.  
  1219.   for (ptr = diff; ptr; ptr = D_NEXT (ptr))
  1220.     {
  1221.       char x[2];
  1222.  
  1223.       switch (ptr->correspond)
  1224.     {
  1225.     case DIFF_ALL:
  1226.       x[0] = '\0';
  1227.       dontprint = 3;    /* Print them all */
  1228.       oddoneout = 3;    /* Nobody's odder than anyone else */
  1229.       break;
  1230.     case DIFF_1ST:
  1231.     case DIFF_2ND:
  1232.     case DIFF_3RD:
  1233.       oddoneout = rev_mapping[(int) ptr->correspond - (int) DIFF_1ST];
  1234.         
  1235.       x[0] = oddoneout + '1';
  1236.       x[1] = '\0';
  1237.       dontprint = eliminate [oddoneout];
  1238.       break;
  1239.     default:
  1240.       fatal ("internal: Bad diff type passed to output");
  1241.     }
  1242.       fprintf (outputfile, "====%s\n", x);
  1243.  
  1244.       /* Go 0, 2, 1 if the first and third outputs are equivalent. */
  1245.       for (i = 0; i < 3;
  1246.        i = (oddoneout == 1 ? skew_increment[i] : i + 1))
  1247.     {
  1248.       int realfile = mapping[i];
  1249.       int
  1250.         lowt = D_LOWLINE (ptr, realfile),
  1251.         hight = D_HIGHLINE (ptr, realfile);
  1252.       
  1253.       fprintf (outputfile, "%d:", i + 1);
  1254.       switch (lowt - hight)
  1255.         {
  1256.         case 1:
  1257.           fprintf (outputfile, "%da\n", lowt - 1);
  1258.           break;
  1259.         case 0:
  1260.           fprintf (outputfile, "%dc\n", lowt);
  1261.           break;
  1262.         default:
  1263.           fprintf (outputfile, "%d,%dc\n", lowt, hight);
  1264.           break;
  1265.         }
  1266.  
  1267.       if (i == dontprint) continue;
  1268.  
  1269.       for (line = 0; line < hight - lowt + 1; line++)
  1270.         {
  1271.           fprintf (outputfile, "  ");
  1272.           for (cp = D_RELNUM (ptr, realfile, line);
  1273.            cp < (D_RELNUM (ptr, realfile, line)
  1274.              + D_RELLEN (ptr, realfile, line));
  1275.            cp++)
  1276.         putc (*cp, outputfile);
  1277.           putc ('\n', outputfile);
  1278.         }
  1279.     }
  1280.     }
  1281. }
  1282.  
  1283. /*
  1284.  * This routine outputs a diff3 set of blocks as an ed script.  This
  1285.  * script applies the changes between file's 2 & 3 to file 1.  It
  1286.  * takes the precise format of the ed script to be output from global
  1287.  * variables set during options processing.  Note that it does
  1288.  * destructive things to the set of diff3 blocks it is passed; it
  1289.  * reverses their order (this gets around the problems involved with
  1290.  * changing line numbers in an ed script).
  1291.  *
  1292.  * Note that this routine has the same problem of mapping as the last
  1293.  * one did; the variable MAPPING maps from file number according to
  1294.  * the argument list to file number according to the diff passed.  All
  1295.  * files listed below are in terms of the argument list.
  1296.  *
  1297.  * Also, occasionally this routine needs the real names of the files
  1298.  * on which it works.  Thus file0, file1, and file2 are the filenames
  1299.  * passed on the command line.
  1300.  *
  1301.  * Returns the number of overlaps.
  1302.  *
  1303.  * See options.h for documentation on the global variables which this
  1304.  * routine pays attention to.
  1305.  */
  1306.  
  1307. int
  1308. output_diff3_edscript (outputfile, diff, mapping, file0, file1, file2)
  1309.      FILE *outputfile;
  1310.      struct diff3_block *diff;
  1311.      int mapping[3];
  1312.      char *file0, *file1, *file2;
  1313. {
  1314.   int rev_mapping[3];
  1315.   int i;
  1316.   int leading_dot;
  1317.   int overlap_count = 0;
  1318.   struct diff3_block *newblock, *thisblock;
  1319.   char *cp;
  1320.  
  1321.   leading_dot = 0;
  1322.  
  1323.   for (i = 0; i < 3; i++)
  1324.     rev_mapping [mapping [i]] = i;
  1325.  
  1326.   newblock = reverse_diff3_blocklist (diff);
  1327.  
  1328.   for (thisblock = newblock; thisblock; thisblock = thisblock->next)
  1329.     {
  1330.       /* Must do mapping correctly.  */
  1331.       enum diff_type type
  1332.     = ((thisblock->correspond == DIFF_ALL) ?
  1333.        DIFF_ALL :
  1334.        ((enum diff_type)
  1335.         (((int) DIFF_1ST)
  1336.          + rev_mapping [(int) thisblock->correspond - (int) DIFF_1ST])));
  1337.  
  1338.       /* If we aren't supposed to do this output block, skip it */
  1339.       if (type == DIFF_2ND || type == DIFF_1ST
  1340.       || (type == DIFF_3RD && dont_write_simple)
  1341.       || (type == DIFF_ALL && dont_write_overlap))
  1342.     continue;
  1343.  
  1344.       if (flagging && type == DIFF_ALL)
  1345.     /* Do special flagging */
  1346.     {
  1347.  
  1348.       /* Put in lines from FILE2 with bracket */
  1349.       fprintf (outputfile, "%da\n",
  1350.            D_HIGHLINE (thisblock, mapping [FILE0]));
  1351.       fprintf (outputfile, "=======\n");
  1352.       for (i = 0;
  1353.            i < D_NUMLINES (thisblock, mapping [FILE2]);
  1354.            i++)
  1355.         {
  1356.           if (D_RELNUM (thisblock, mapping[FILE2], i)[0] == '.')
  1357.         { leading_dot = 1; fprintf(outputfile, "."); }
  1358.           for (cp = D_RELNUM (thisblock, mapping [FILE2], i);
  1359.            cp < (D_RELNUM (thisblock, mapping [FILE2], i)
  1360.              + D_RELLEN (thisblock, mapping [FILE2], i));
  1361.            cp++)
  1362.         putc (*cp, outputfile);
  1363.           putc ('\n', outputfile);
  1364.         }
  1365.       fprintf (outputfile, ">>>>>>> %s\n.\n", file2);
  1366.       overlap_count++;
  1367.  
  1368.       /* Add in code to take care of leading dots, if necessary. */
  1369.       if (leading_dot)
  1370.         {
  1371.           fprintf (outputfile, "%d,%ds/^\\.\\./\\./\n",
  1372.                D_HIGHLINE (thisblock, mapping [FILE0]) + 1,
  1373.                (D_HIGHLINE (thisblock, mapping [FILE0])
  1374.             + D_NUMLINES (thisblock, mapping [FILE2])));
  1375.           leading_dot = 0;
  1376.         }
  1377.  
  1378.       /* Put in code to do initial bracket of lines from FILE0  */
  1379.       fprintf (outputfile, "%da\n<<<<<<< %s\n.\n",
  1380.            D_LOWLINE (thisblock, mapping[FILE0]) - 1,
  1381.            file0);
  1382.     }
  1383.       else if (D_NUMLINES (thisblock, mapping [FILE2]) == 0)
  1384.     /* Write out a delete */
  1385.     {
  1386.       if (D_NUMLINES (thisblock, mapping [FILE0]) == 1)
  1387.         fprintf (outputfile, "%dd\n",
  1388.              D_LOWLINE (thisblock, mapping [FILE0]));
  1389.       else
  1390.         fprintf (outputfile, "%d,%dd\n",
  1391.              D_LOWLINE (thisblock, mapping [FILE0]),
  1392.              D_HIGHLINE (thisblock, mapping [FILE0]));
  1393.     }
  1394.       else
  1395.     /* Write out an add or change */
  1396.     {
  1397.       switch (D_NUMLINES (thisblock, mapping [FILE0]))
  1398.         {
  1399.         case 0:
  1400.           fprintf (outputfile, "%da\n",
  1401.                D_HIGHLINE (thisblock, mapping [FILE0]));
  1402.           break;
  1403.         case 1:
  1404.           fprintf (outputfile, "%dc\n",
  1405.                D_HIGHLINE (thisblock, mapping [FILE0]));
  1406.           break;
  1407.         default:
  1408.           fprintf (outputfile, "%d,%dc\n",
  1409.                D_LOWLINE (thisblock, mapping [FILE0]),
  1410.                D_HIGHLINE (thisblock, mapping [FILE0]));
  1411.           break;
  1412.         }
  1413.       for (i = 0;
  1414.            i < D_NUMLINES (thisblock, mapping [FILE2]);
  1415.            i++)
  1416.         {
  1417.           if (D_RELNUM (thisblock, mapping [FILE2], i)[0] == '.')
  1418.         { leading_dot = 1; fprintf (outputfile, "."); }
  1419.           for (cp = D_RELNUM (thisblock, mapping [FILE2], i);
  1420.            cp < (D_RELNUM (thisblock, mapping [FILE2], i)
  1421.              + D_RELLEN (thisblock, mapping [FILE2], i));
  1422.            cp++)
  1423.         putc (*cp, outputfile);
  1424.           putc ('\n', outputfile);
  1425.         }
  1426.       fprintf (outputfile, ".\n");
  1427.       
  1428.       /* Add in code to take care of leading dots, if necessary. */
  1429.       if (leading_dot)
  1430.         {
  1431.           fprintf (outputfile, "%d,%ds/^\\.\\./\\./\n",
  1432.                D_HIGHLINE (thisblock, mapping [FILE0]) + 1,
  1433.                (D_HIGHLINE (thisblock, mapping [FILE0])
  1434.             + D_NUMLINES (thisblock, mapping [FILE2])));
  1435.           leading_dot = 0;
  1436.         }
  1437.     }
  1438.     }
  1439.   if (finalwrite) fprintf (outputfile, "w\nq\n");
  1440.   return overlap_count;
  1441. }
  1442.  
  1443. /*
  1444.  * Reverse the order of the list of diff3 blocks.
  1445.  */
  1446. struct diff3_block *
  1447. reverse_diff3_blocklist (diff)
  1448.      struct diff3_block *diff;
  1449. {
  1450.   register struct diff3_block *tmp, *next, *prev;
  1451.  
  1452.   for (tmp = diff, prev = (struct diff3_block *) 0;
  1453.        tmp; tmp = next)
  1454.     {
  1455.       next = tmp->next;
  1456.       tmp->next = prev;
  1457.       prev = tmp;
  1458.     }
  1459.   
  1460.   return prev;
  1461. }
  1462.  
  1463. int
  1464. myread (fd, ptr, size)
  1465.      int fd, size;
  1466.      char *ptr;
  1467. {
  1468.   int result = read (fd, ptr, size);
  1469.   if (result < 0)
  1470.     perror_with_exit ("Read failed");
  1471.   return result;
  1472. }
  1473.  
  1474. VOID *
  1475. xmalloc (size)
  1476.      int size;
  1477. {
  1478.   VOID *result = (VOID *) malloc (size);
  1479.   if (!result)
  1480.     fatal ("Malloc failed");
  1481.   return result;
  1482. }
  1483.  
  1484. VOID *
  1485. xrealloc (ptr, size)
  1486.      VOID *ptr;
  1487.      int size;
  1488. {
  1489.   VOID *result = (VOID *) realloc (ptr, size);
  1490.   if (!result)
  1491.     fatal ("Malloc failed");
  1492.   return result;
  1493. }
  1494.  
  1495. fatal (string)
  1496.      char *string;
  1497. {
  1498.   fprintf (stderr, "%s: %s\n", argv0, string);
  1499.   exit (1);
  1500. }
  1501.  
  1502. perror_with_exit (string)
  1503.      char *string;
  1504. {
  1505.   perror (string);
  1506.   exit (1);
  1507. }
  1508.